<template>
  <div class="date-editor">
    <input
      type="datetime-local"
      v-model="currentValue"
      class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary text-sm"
      @input="$emit('input', currentValue)"
    >
    <div class="text-xs text-gray-500 mt-1" v-if="hintText">
      {{ hintText }}
    </div>
  </div>
</template>

<script>
import { ref, watch, computed } from 'vue';

export default {
  props: {
    value: {
      type: String,
      default: ''
    },
    // 可选：仅日期模式
    dateOnly: {
      type: Boolean,
      default: false
    }
  },
  emits: ['input'],
  setup(props) {
    const currentValue = ref(formatValue(props.value));

    // 根据模式格式化值
    function formatValue(value) {
      if (!value) return '';
      
      // 尝试解析日期
      const date = new Date(value);
      if (isNaN(date.getTime())) return value;
      
      // 仅日期模式
      if (props.dateOnly) {
        return date.toISOString().split('T')[0];
      }
      
      // 日期时间模式
      return date.toISOString().slice(0, 16);
    }

    // 计算输入类型和提示文本
    const inputType = computed(() => props.dateOnly ? 'date' : 'datetime-local');
    const hintText = computed(() => props.dateOnly ? '请选择日期' : '请选择日期和时间');

    // 监听外部值变化
    watch(
      () => props.value,
      (newVal) => {
        currentValue.value = formatValue(newVal);
      }
    );

    return {
      currentValue,
      inputType,
      hintText
    };
  }
};
</script>
    